import {
  Shader,
  ShaderData,
  ShaderProperty,
  ShaderPool,
  ShaderProgram,
  ShaderProgramPool,
  ShaderMacro,
  ShaderMacroCollection,
  ShaderDataGroup,
  ShaderLib
} from "@nirvana/shaders";
import { Color } from "@nirvana/math";

import { WebGLCanvas } from "@nirvana/canvas";
import { VertexBufferData, IndexBufferData, DataElement } from "@nirvana/core";

// meta(viewport)、devicePixelRatio、canvas.width

// 使用使用 Canvas
let canvas = document.getElementById("engine-nirvana");
// console.log(canvas);

const webCanvas = new WebGLCanvas(canvas, {
  // fullScreen: true, // 自动放大全屏
  // fixWidth: 500, // 放大
  // auto: true // 页面设置了canvas 样式
  // 2d: true,
});
// webCanvas.fullScreen();
const engine = webCanvas.engine;
const gl = engine.gl;

const cVS = `
attribute vec3 aVertexPosition;
attribute vec4 aVertexColor;

varying lowp vec4 vColor;

void main(void) {
  gl_Position = vec4(aVertexPosition, 1.0);
  vColor = aVertexColor;
}`;
const cFS = `
varying lowp vec4 vColor;
void main(void) {
  gl_FragColor = vColor;
}`;
const colorDemo = Shader.create("colorDemo", cVS, cFS);
console.log(colorDemo, Shader.find("colorDemo"));
const pool4: ShaderProgramPool = new ShaderProgramPool();
const shaderMacroCollection: ShaderMacroCollection = new ShaderMacroCollection();
console.log(shaderMacroCollection);
const colorProgram: ShaderProgram = colorDemo.getShaderProgram(engine.gl, shaderMacroCollection, pool4);
console.log("color", colorProgram);

const pos = new VertexBufferData(new Float32Array([0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5]), [
  new DataElement("aVertexPosition", 2, gl.FLOAT, false, 0, 0)
]);
const col = new VertexBufferData(
  new Float32Array([
    1.0,
    1.0,
    1.0,
    1.0, // 白
    1.0,
    0.0,
    0.0,
    1.0, // 红
    0.0,
    1.0,
    0.0,
    1.0, // 绿
    0.0,
    0.0,
    1.0,
    1.0 // 蓝
  ]),
  [new DataElement("aVertexColor", 4, gl.FLOAT, false, 0, 0)]
);
pos.create(gl);
col.create(gl);

const colorShaderData: ShaderData = new ShaderData(ShaderDataGroup.Material);
console.log(ShaderDataGroup, colorShaderData);

engine.update = (gl) => {
  // console.log('--');
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  // 用上面指定的颜色清除缓冲区
  gl.clear(gl.COLOR_BUFFER_BIT);
  // 颜色 start 三
  colorProgram.bind();
  pos.upload(colorProgram._glProgram, gl);
  col.upload(colorProgram._glProgram, gl);
  // gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  pos.draw(gl);
  // 颜色 end
};
